
// The various drawing sub-windows
// Will be assembled to form the actual viewing window

// TODO: move to units.h I guess
var SCREEN_WIDTH = 320, SCREEN_HEIGHT = 240
var SPACE_WIDTH = 240
var SPACE_HEIGHT = 240 
var SAFE_X = 0, SAFE_Y = 0
var STATUS_WIDTH = SCREEN_WIDTH - SPACE_WIDTH - SAFE_X * 2, STATUS_HEIGHT = SPACE_HEIGHT

function DrawingContext(x, y, w, h, background) {
	this.canvas = document.createElement("canvas")
	this.canvas.width = this.w = w
	this.canvas.height = this.h = h
	this.x = x
	this.y = y
	this.ctx = this.canvas.getContext("2d")
	this.visible = false
	this.background = background
}
DrawingContext.prototype = {
	clear: function () {
		this.ctx.clearRect(0, 0, this.w, this.h)
		if (this.background) {
			this.ctx.fillStyle = this.background
			this.ctx.fillRect(0, 0, this.w, this.h)
		}
	},
	drawframe: function (frame, x, y, z) {
		this.ctx.save()
		this.ctx.translate(x, y)
		if (z) this.ctx.scale(z, z)
		//this.ctx.fillStyle = "rgba(255,255,255,0.2)"
		//this.ctx.fillRect(-frame.hotspotx, -frame.hotspoty, frame.img.width, frame.img.height)
		this.ctx.drawImage(frame.img, -frame.hotspotx, -frame.hotspoty)
		this.ctx.restore()
	},
	drawline: function (color, x0, y0, x1, y1, z) {
		this.ctx.strokeStyle = color
		this.ctx.lineWidth = 1
		this.ctx.beginPath()
		this.ctx.moveTo(x0, y0)
		this.ctx.lineTo(x1, y1)
		this.ctx.stroke()
		//console.log("stroking", x0, y0, x1, y1, color)
	},
	drawpoint: function (color, x, y) {
		this.ctx.fillStyle = color
		this.ctx.fillRect(x, y, 1, 1)
	},
}

var context = {
	contextList: [],
	init: function () {
		this.create("space", SAFE_X, SAFE_Y, SPACE_WIDTH, SPACE_HEIGHT, "black")
		this.create("status", SPACE_WIDTH + SAFE_X, SAFE_Y, STATUS_WIDTH, STATUS_HEIGHT)

		// The assmebled contexts before they're drawn to the full canvas
		this.mscreen = new DrawingContext(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)

		// The screen canvas itself
		this.screen = document.getElementById("screen")
		this.screen.width = 2 * SCREEN_WIDTH
		this.screen.height = 2 * SCREEN_HEIGHT
		this.sctx = this.screen.getContext("2d")
		this.sctx.scale(2, 2)
		//this.sctx.imageSmoothingEnabled = false
	},
	create: function (cname, sx, sy, px, py, background) {
		var c = new DrawingContext(sx, sy, px, py, background)
		this.contextList.push(c)
		this[cname] = c
	},
	unhide: function (cname) {
		this[cname].visible = true
	},
	hideAll: function () {
		this.contextList.forEach(function (c) {
			c.visible = false
		})
	},
	clearAll: function () {
		this.contextList.forEach(function (c) {
			c.clear()
		})
	},
	clearScreen: function () {
		this.mscreen.clear()
	},
	assemble: function () {
		for (var j = 0 ; j < this.contextList.length ; ++j) {
			var c = this.contextList[j]
			if (c.visible) this.mscreen.ctx.drawImage(c.canvas, c.x, c.y)
		}
	},
	flip: function () {
		this.assemble()
		this.sctx.drawImage(this.mscreen.canvas, 0, 0)
	},
}


